import React, { Fragment, useEffect, useRef, useState } from 'react';
import styled from 'styled-components';
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faTimes, faSearch } from '@fortawesome/free-solid-svg-icons';
import PropTypes from 'prop-types';
import useKeyHandler from '../hooks/useKeyHandler';

const SerachDiv = styled.div.attrs({
  className: "d-flex align-items-center justify-content-between"
})`
  border-bottom: 1px solid #fff;
  span {
    color: #fff;
    padding: 0 10px;
    font: normal 16px/40px "微软雅黑";  
  }
  input {
    border: none;
    border-radius: 4px;
    margin-left: 10px;
  }
  .button {
    cursor: pointer;
  }
`;

SearchFile.propTypes = {
  title: PropTypes.string,
  onSearch: PropTypes.func.isRequired
};
SearchFile.defaultProps = {
  title: "FISHの文档"
}

export default function SearchFile({ title, onSearch }) {
  
  const [searchAcitve, setSearchAcitve] = useState(false);
  const [value, setValue] = useState("");
  const input = useRef(null);
  const enterPressed = useKeyHandler(13);
  const escPressed = useKeyHandler(27);

  const closeSearch = () => {
    setSearchAcitve(false);
    setValue("");
    onSearch("");
  };

  // 判断 hook 逻辑
  useEffect(() => {
    if (enterPressed && searchAcitve) onSearch(value);
    if (escPressed && searchAcitve) closeSearch();
  });
  
  // 聚焦
  useEffect(() => {
    if (searchAcitve) {
      input.current.focus();
    }
  }, [searchAcitve]);
  return (
    <Fragment>
      {
        !searchAcitve ?
        <SerachDiv>
          <span>{ title }</span>
          <span className="button" onClick={() => setSearchAcitve(true)}>
            <FontAwesomeIcon icon={faSearch}></FontAwesomeIcon>
          </span>
        </SerachDiv>
        : 
        <SerachDiv>
          <input 
            value={value} type="text"
            ref={input} 
            onChange={e => setValue(e.target.value)} />
          <span className="button" onClick={closeSearch}>
            <FontAwesomeIcon icon={faTimes}></FontAwesomeIcon>
          </span>
        </SerachDiv>
      }
    </Fragment>
  );
};